package camid.services.nameservice;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.http.conn.util.InetAddressUtils;

import com.google.common.net.InetAddresses;

import camid.distribution.protocol.Endpoint;

public class NameServiceUtil {

	/**
	 * Auto discovery for host current hostname
	 * 
	 * @param portNumber
	 * @return
	 */
	public static Endpoint getLocalEndpoint(int portNumber) {
		String host = getNetAddress();
		Endpoint ep = new Endpoint(host, portNumber);
		return ep;
	}
	
	public static String getNetAddress()
	{
		String address = null;
		try {
			Enumeration<NetworkInterface> netifs = NetworkInterface.getNetworkInterfaces();
			while(netifs.hasMoreElements())
			{
				NetworkInterface netif = netifs.nextElement();
				if(netif.isUp() && !netif.isLoopback() && !netif.isPointToPoint())
				{
					Enumeration<InetAddress> iaddrs = netif.getInetAddresses();
					while(iaddrs.hasMoreElements())
					{
						InetAddress iaddr = iaddrs.nextElement();
						if(iaddr instanceof Inet4Address)
						{
							address = iaddr.getHostAddress();
							break;
						}
					}
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return address;
	}

	public static String getHostname() {
		String hostname = null;
		
//		InetAddresses.
		
		return hostname;
	}

}
